//
//  ICDatabaseManager.m
//  ICome
//
//  Created by ENN on 16/3/7.
//  Copyright © 2016年 iCom. All rights reserved.
//

#import "ICDatabaseManager.h"
#import "FMDB.h"
#import "NSBundle+iComeSDK.h"
NSString *const messageDbName = @"IcomMessage.db";    // 消息库


#define messageDbPath [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:messageDbName]


@implementation ICDatabaseManager

static id _instance;

+ (instancetype)shareManager
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[ICDatabaseManager alloc] init];
    });
    return _instance;
}

- (instancetype)init
{
    if (self = [super init]) {
        self.messageQueue  = [[FMDatabaseQueue alloc] initWithPath:messageDbPath];
        [self createMessageTables];
    }
    return self;
}

- (void)createMessageTables
{
    
    NSBundle *fileBundle = [NSBundle ic_getFileBundle];
    
    NSLog(@"--%@",messageDbPath);
    NSString *path = [fileBundle pathForResource:@"ICMessageTables" ofType:@"sql"];
    NSError *error = nil;
    NSString *sql  = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];
    if (error) NSLog(@"load sql error");
    [self.messageQueue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        [db executeStatements:sql];
    }];
}



- (void)dropAllTable
{
    [self.messageQueue inDatabase:^(FMDatabase *db) {
        FMResultSet *set = [db executeQuery:@"select name from sqlite_master where type='table'"];
        NSMutableArray *dropTables = [NSMutableArray arrayWithCapacity:0];
        while ([set next]) {
            NSString *tableName = [set stringForColumnIndex:0];
            if (tableName) {
                [dropTables addObject:tableName];
            }
        }
        [set close];
        for (NSString *tableName in dropTables) {
            if ([tableName hasPrefix:@"sqlite_"] == NO) {
                NSString *dropTable = [NSString stringWithFormat:@"drop table %@", tableName];
                [db executeUpdate:dropTable];
            }
        }
    }];
}


- (void)deleteTable:(NSString *)tableName {
    NSString * sql = [NSString stringWithFormat:@"delete from %@", tableName];
    [self.messageQueue inDatabase:^(FMDatabase *db) {
        if ([db executeUpdate:sql]) {
            NSLog(@"%@成功", tableName);
        }else{
            NSLog(@"%@失败", tableName);
        }
    }];
}

// 数据表结构升级操作
- (void)changeDBData:(FMDatabase *)db tableName:(NSString *)tableName createSql:(NSString *)createSql {
    
    [self.messageQueue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        [db open];
        // 变更数据库表为一个旧数据表
        NSString *sqlStr = [NSString stringWithFormat:@"ALTER TABLE %@ RENAME TO %@", tableName, [tableName stringByAppendingString:@"_Old"]];
        // 执行SQL语句操作
        [db executeUpdate:sqlStr];
        // 创建新的数据表
        NSString *executeStr = createSql;
        BOOL bRet = [db executeUpdate:executeStr];
        if (bRet) {
            // 从旧数据表把旧数据插入新的数据表中 .. 升级语句需要weex内部自己定义sql
            NSString *insertSql = [NSString stringWithFormat:@"INSERT INTO %@ SELECT * ,'','','' FROM %@", tableName, [tableName stringByAppendingString:@"_Old"]];
           BOOL ins = [db executeUpdate:insertSql];
            NSLog(@"%d", ins);
        }
        // 删除旧的数据表
        [db executeUpdate:[NSString stringWithFormat:@"DROP TABLE %@",      [tableName stringByAppendingString:@"_Old"]]];
        [db close];
    }];
}

@end

